<?php

namespace App\Controller;

use App\Entity\Comment;
use App\Entity\Conference;
use App\Message\CommentMessage;
use App\Repository\CommentRepository;
use App\Repository\ConferenceRepository;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Notifier\Notification\Notification;
use Symfony\Component\Notifier\NotifierInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class ConferenceController extends BaseController
{

    /**
     * @Route("/")
     */
    public function indexNoLocale()
    {
        return $this->redirectToRoute('homepage', ['_locale' => 'en']);
    }

    /**
     * @Route("/{_locale<%app.supported_locales%>}/", name="homepage")
     */
    public function index(ConferenceRepository $conferenceRepository)
    {
        $this->parameters['conferences'] = $conferenceRepository->findAll();
        $response = new Response($this->container->get("twig")->render('conference/index.html.twig',$this->parameters));
        $response->setSharedMaxAge(3600);
        return $response;
    }

    /**
     * @Route("/{_locale<%app.supported_locales%>}/conference_header", name="conference_header")
     */
    public function conferenceHeader(ConferenceRepository $conferenceRepository)
    {
        $response = new Response($this->container->get("twig")->render('conference/header.html.twig', [
            'conferences' => $conferenceRepository->findAll(),
        ]));
        $response->setSharedMaxAge(3600);

        return $response;
    }

    /**
     * @Route("/{_locale<%app.supported_locales%>}/conference/{slug}",name="conference")
     * @param Request $request
     * @param Conference $conference
     * @param CommentRepository $commentRepository
     * @param MessageBusInterface $bus
     * @param NotifierInterface $notifier
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
     */
    public function show(Request $request,Conference $conference,CommentRepository $commentRepository,MessageBusInterface $bus,NotifierInterface $notifier)
    {
        $offset = max(0, $request->query->getInt('offset', 0));
        $paginator = $commentRepository->getCommentPaginator($conference, $offset);
        $comment = new Comment();
        $form = $this->createForm("App\Form\CommentFormType",$comment);
        $form->handleRequest($request);
        if($form->isSubmitted() and $form->isValid()){
            $em = $this->container->get('doctrine')->getManager();
            $comment->setConference($conference);
            $context = [
                'user_ip' => $request->getClientIp(),
                'user_agent' => $request->headers->get('user-agent'),
                'referrer' => $request->headers->get('referer'),
                'permalink' => $request->getUri(),
            ];
            try{
//                if (2 === $spamChecker->getSpamScore($comment, $context)) {
//                    throw new \RuntimeException('垃圾邮件，走开！');
//                }
                /** @var UploadedFile $photo */
                if($photo = $form['photo']->getData()){
                    $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
                    $upload_photos_dir = $this->getParameter("upload_photos");
                    if(!is_dir($upload_photos_dir))mkdir($upload_photos_dir,0777,true);
                    $photo->move($upload_photos_dir,$filename);
                    $comment->setPhotoFilename($filename);
                }
            }catch (FileException $exception){
                $formError = new FormError("文件上传失败".$exception->getMessage());
            }catch (\Exception $exception){
                $formError = new FormError("评论失败".$exception->getMessage());
            }
            if(isset($formError))$form->addError($formError);
            if (!isset($formError)){
                $em->persist($comment);
                $em->flush();
                $reviewUrl = $this->generateUrl('review_comment', ['id' => $comment->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
                $bus->dispatch(new CommentMessage($comment->getId(), $reviewUrl, $context));
                $notifier->send(new Notification('Thank you for the feedback; your comment will be posted after moderation.', ['browser']));
                return $this->redirectToRoute("conference",['slug'=>$conference->getSlug()]);
            }
        }
        if ($form->isSubmitted()) {
            $notifier->send(new Notification('Can you check your submission? There are some problems with it.', ['browser']));
        }

        return $this->render('conference/show.html.twig', array_merge([
            'conference' => $conference,
            'comments' => $paginator,
            'previous' => $offset - CommentRepository::PAGINATOR_PER_PAGE,
            'next' => min(count($paginator), $offset + CommentRepository::PAGINATOR_PER_PAGE),
            'comment_form'=>$form->createView()
        ],$this->parameters));
    }


}
